<!--
 * @Author: your name
 * @Date: 2020-05-04 09:51:17
 * @LastEditTime: 2020-05-13 11:24:49
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \v-nw-h5\src\pages\im\imVideo.vue
 -->
<template>
    <div class="imVideo">
        <div v-show="!incomingCallPage">
            <div class='video-calling-preview-item' id='preview' ref="preview" v-show="!videoCallingDesc">
                <video class='preview' autoplay=true></video>
            </div>
            <!-- 切换摄像头 -->
            <div class='ui-flex justify-center center switch-camera-title' id='switch' ref="switch"
                 @click="switchTheCamera">
                <img class="im-chat-input-icon" src="../../assets/images/im/switch-icon.png" alt="">
            </div>
            <!-- <div class="durationText">通话时间{{callDurationDesc}}</div> -->
            <div class='video-called-small-preview-item' id="small" ref="small" @click="swapPlaces"
                 v-show="videoCallingDesc">
                <video autoplay=true class="small-video"></video>
            </div>
            <div class='video-called-large-preview-item' id='large' ref="large" v-show="videoCallingDesc">
                <video autoplay=true class="large-video"></video>
            </div>
            <div class='ui-flex justify-center center hangup-title' id='hangup' ref="hangup" @click="hangup">
                <img class="im-chat-input-icon" src="../../assets/images/im/hangup.png" alt="">
            </div>
        </div>
        <div v-show="incomingCallPage">
            <div class="userInfo">
                <img :src="userInfo.photo" alt="">
                <div>{{userInfo.showName}}</div>
            </div>
            <div id='doIncomingCall' class='incoming-call-page'>
                <!-- 拒绝接听 -->
                <div class='incoming-ignore-btn' @click='ignore'>
                    <img class="im-chat-input-icon" src="../../assets/images/im/hangup.png" alt="">
                </div>
                <!-- 接听 -->
                <div class='incoming-answer-btn' @click="answer">
                    <img class="im-chat-input-icon" src="../../assets/images/im/answer-icon.png" alt="">
                </div>
            </div>
        </div>

    </div>
</template>
<script>
    import {Toast} from "mint-ui";
    import GoodLooking from '../../pages/goodLooking/NewLook'
    import SDK from '../../assets/js/im/NIM_Web_SDK_v7.5.0';
    import WebRTC from '../../assets/js/im/NIM_Web_WebRTC_v7.5.0'
    import {mapGetters} from 'vuex'

    window.Netcall = WebRTC;
    window.NIM = SDK.NIM;
    NIM.use(WebRTC);
    // var hrt = document.documentElement.clientHeight
    // window.onload = function(){
    //   document.getElementById('imVideo').style.height = hrt + 'px'
    // }
    window.self = null
    export default {
        name: 'imVideo',
        props: {
            chatGroupId: {
                type: String,
            },
            getNim:{
                type:Object
            }
        },
        data() {
            return {
                /*页面元素的值*/
                userInfo: {},
                account: '',
                password: '',
                calleeAccount: 'pg_manager_1034',
                incomingCallDesc: 'xxx邀请你语音聊天',
                callingText: '正在呼叫，请稍后...',
                durationText: '00:00',
                callDurationDesc: '通话时长: 01:40',
                cameraOpen: true,
                micOpen: true,
                sliderNum: 10,

                /*sdk实例化对象*/
                nim: null,
                netcall: null,
                /*业务逻辑变量*/
                localVideoStream: null,
                callType: 'video',
                toastTimer: null,
                callTimeoutTimer: null,
                callHintTimer: null,
                incomingCallTimeoutTimer: null,
                incomingCallHintTimer: null,
                incomingCallInfo: null, //该demo不考虑连续多人同时呼叫的场景，针对这种场景，用户可以根据自己的业务做相关逻辑
                callDurationTimer: null,
                currentPage: 'login',
                currentNetStatus: null,
                startTime: null,
                devices: {
                    list: [],
                    index: 0,
                },

                /* 控制元素的展示 */
                //登录页面
                logoIcon: true,
                loginPage: true,
                //呼叫页面
                callPage: false,
                //呼叫中页面
                callingPage: false,
                preview: false,
                audioCallingDesc: false,
                videoCallingDesc: false,
                //通话页面
                calledPage: false,
                largeVideo: false,
                smallVideo: false,
                durationItem: false,
                networkItem: false,
                callDurationItem: false,
                slider: false,
                //来电页面
                incomingCallPage: false,
            }
        },
        computed: {
            isChatGroupId() {
                let id
                if (this.$route.query.chatGroupId) {
                    id = this.$route.query.chatGroupId
                } else {
                    id = this.chatGroupId
                }
                return id
            },
        },
        created() {


            // this.$store.commit('initWebrtc', { fn: this.initWebrtc })
            // this.netcall = this.$store.state.logic.groupChat.netcall
            // this.nim = this.$store.state.logic.groupChat.nvWa-index-img
            // this.nim.getCaptureVolume()
            // this.calleeAccount = this.$route.query.from

        },

        mounted() {
            if (this.isChatGroupId) {
                let url = `${this.NW_API_API_LOCALE_VERSION}/av/chat/info`;
                let params = {
                    userId: this.userId,
                    groupChat: true,
                    targetAccount: this.isChatGroupId,
                    customerType: this.$route.query.customerType || '',
                    customerKey: this.$route.query.customerKey || ''
                }
                this.xurl.get(url, params).then((data) => {
                    if (data.success) {
                        this.userInfo = JSON.parse(data.result.extraParamsStr)
                        this.calleeAccount = data.result.targetChatAccount

                    }

                })
            }
            //   setTimeout(() => {

            //       console.log(this.chatGroupId,'chatGroupId');
            //   }, 3000);
            this.initWebrtc()
        },
        beforeDestroy() {
        },
        methods: {
            initWebrtc: function () {
                //   this.netcall = this.$store.state.logic.groupChat.netcall
                this.nim = this.getNim
                //   this.nim = window.sessionStorage.getItem("groupChat")
                console.log('开始初始化 音视频 sdk...')
                this.netcall = WebRTC.getInstance({
                    container: null, //本端视频展示的容器，不需要初始化的时候赋值
                    remoteContainer: null, //远端视频展示的容器，不需要初始化的时候赋值
                    chromeId: null, //演示功能是否使用插件
                    debug: true,
                    nim: this.nim,
                })
                // this.netcall = window.sessionStorage.getItem("sessionData") ? window.sessionStorage.getItem("sessionData") : WebRTC.getInstance({
                //   container: null, //本端视频展示的容器，不需要初始化的时候赋值
                //   remoteContainer: null, //远端视频展示的容器，不需要初始化的时候赋值
                //   chromeId: null, //演示功能是否使用插件
                //   debug: true,
                //   nim: this.nim,
                // })
                window.sessionStorage.setItem('netcall', this.netcall);
                WebRTC.checkCompatibility().then(function (data) {
                    console.log('兼容性检查', data)
                })
                //监听sdk的事件
                this.netcall.on('beCalling', this.beCallingHandler)
                this.netcall.on('callRejected', this.callRejectedHandler)
                this.netcall.on('callAccepted', this.callAcceptedHandler)
                this.netcall.on('remoteTrack', this.remoteTrackHandler)
                this.netcall.on('hangup', this.hangupHandler)
                //   this.netcall.on('gatewayClosed', this.gatewayClosedHandler)
                //   this.netcall.on('error', this.errorHandler)
                console.log('登录完成，进入呼叫页面')
                //进入呼叫页面
                this.currentPage = 'call'
                this.callPage = true
            },

            firestEnterCalledPage: function () {
                console.warn('进入通话页面, type: ', this.callType)
                //进入通话页面
                //   document.getElementById("rangeslider__handle").style.bottom = "70px"　
                this.sliderNum = 10
                this.currentPage = 'called'
                this.durationText = '00:00'
                this.startTime = Date.now()
                this.incomingCallPage = false
                this.callingPage = false
                this.calledPage = true
                this.durationItem = true
                this.networkItem = true
                this.callDurationItem = false
                //   if (this.callType === 'audio') {
                //     console.warn('音频通话界面')
                //     this.largeVideo = false
                //     this.smallVideo = false
                //   } else if (this.callType === 'video'){
                //     console.warn('视频通话界面')
                //     this.largeVideo = true
                //     this.smallVideo = true
                //   }
                //const self = this
                this.callDurationTimer = setInterval(() => {
                    this.durationText = secondToDate(Date.now() - this.startTime)
                }, 1000)
            },

            beginMeidaCall: function () {
                this.netcall.startRtc()
                    .then(data => {
                        this.videoCallingDesc = true
                        console.log("连接媒体网关成功: ", data)
                        this.openTheMic().then(data => {
                            console.log('begin 开启mic成功')
                            if (this.callType === 'video') {
                                this.openTheCamera().then(data => {
                                    console.log('begin 开启camera成功')
                                    this.firestEnterCalledPage()
                                }).catch(error => {
                                    console.error('begin 开启camera失败: ', error)
                                })
                            } else {
                                this.firestEnterCalledPage()
                            }
                        }).catch(error => {
                            console.error('begin 开启mic失败: ', error)
                        })

                    })
                    .catch(function (error) {
                        console.error('连接媒体网关失败: ', error)
                    })
            },

            audioCall: function () {
                this.callType = 'audio'
                this.call()
            },

            videoCall: function () {
                this.callType = 'video'
                this.call()
            },

            call: function () {
                console.log('%s呼叫%s', this.callType, this.calleeAccount)
                /*进入呼叫中页面*/
                this.currentPage = 'calling'
                this.callingText = '正在呼叫，请稍后...'
                //   Toast(this.callingText);
                this.callPage = false
                if (this.callType === 'audio') {
                    // this.$refs.audioCallingDesc.style.color = '#000'
                    this.audioCallingDesc = true
                    this.videoCallingDesc = false
                    this.preview = false
                } else {
                    // this.$refs.videoCallingDesc.style.color = '#FFF'
                    this.audioCallingDesc = false
                    this.videoCallingDesc = false
                    this.preview = true
                    this.previewLocalCamera()
                }
                this.callingPage = true
                //启动呼叫超时定时器
                const self = this
                this.callTimeoutTimer = setTimeout(() => {
                    console.log('超时无人接听，自动挂断')
                    this.$store.commit('videoImHidden', {hidden: false})
                    this.callingText = '无人接听'
                    Toast(this.callingText);
                    // this.$refs.audioCallingDesc.style.color = 'red'
                    self.callTimeoutTimer = null
                    if (self.currentPage === 'calling') {
                        self.cleanCallTimer()
                        //const self = this
                        setTimeout(() => {
                            //回到呼叫页面
                            self.currentPage = 'call'
                            self.enterPreviousPage()
                        }, 2 * 1000)
                    }
                }, 60 * 1000)

                this.netcall.call({
                    type: this.callType === 'audio' ? Netcall.NETCALL_TYPE_AUDIO : Netcall.NETCALL_TYPE_VIDEO,
                    account: this.calleeAccount,
                    pushConfig: {
                        custom: JSON.stringify({
                            extraParamsStr: this.userInfo
                        })
                    }, //推送消息
                    webrtcEnable: true,
                    sessionConfig: {
                        videoQuality: Netcall.CHAT_VIDEO_QUALITY_HIGH,
                        videoFrameRate: Netcall.CHAT_VIDEO_FRAME_RATE_15,
                        videoBitrate: 0,
                        recordVideo: false,
                        recordAudio: false,
                        singleRecord: false,
                        highAudio: false,
                        rtmpUrl: "",
                        rtmpRecord: false,
                        splitMode: Netcall.LAYOUT_SPLITLATTICETILE
                    }
                }).then(data => {
                    console.log("呼叫成功, data=%o", data);
                }).catch(error => {
                    //   this.$store.commit('videoImHidden',{hidden:false})
                    console.error("呼叫失败，error=%o", error);
                    this.callingText = '对方不在线'
                    Toast(this.callingText);
                    // this.$refs.audioCallingDesc.style.color = 'red'
                    // this.$refs.videoCallingDesc.style.color = 'red'
                    if (self.currentPage === 'calling') {
                        // this.$store.commit('videoImHidden',{hidden:false})

                        self.cleanCallTimer()
                        setTimeout(() => {
                            //回到呼叫页面
                            self.currentPage = 'call'
                            self.enterPreviousPage()
                        }, 2 * 1000)
                    }
                })
            },
            beCallingHandler: function (_data) {
                this.$store.commit('videoImHidden', {show: true})
                console.warn("===== 收到 beCalling 事件: ", _data);
                _data.type === 1 ? this.callType = 'audio' : this.callType = 'video'
                this.netcall.control({
                    channelId: _data.channelId,
                    command: Netcall.NETCALL_CONTROL_COMMAND_START_NOTIFY_RECEIVED
                })

                this.netcall.getDevicesOfType(Netcall.DEVICE_TYPE_VIDEO).then(data => {
                    if (!data || data.length <= 0) {
                        console.log("没有获取到摄像头列表: ", data)
                        return
                    }
                    console.warn("摄像头列表: ", data)
                    this.devices.list = data
                    this.devices.index = 0
                }).catch(error => {
                    console.log("获取摄像头列表出错: ", error)
                })

                console.log('进入来电页面')
                this.incomingCallInfo = _data //后面的呼叫会覆盖前面的呼叫，不考虑连续来电的场景
                this.incomingCallDesc = _data.account + '邀请你' + (_data.type === 1 ? '音频' : '视频') + '聊天'
                this.logoIcon = false
                this.loginPage = false
                this.callPage = false
                this.callingPage = false
                this.calledPage = false
                this.incomingCallPage = true

                //启动超时定时器
                this.incomingCallTimeoutTimer = setTimeout(() => {
                    console.log('超时未接听，自动挂断')
                    this.incomingCallDesc = '未接听'
                    self.incomingCallTimeoutTimer = null
                    self.incomingCallHintTimer = setTimeout(() => {
                        self.incomingCallHintTimer = null
                        console.log('挂断来电')
                        self.ignore()
                    }, 2 * 1000)
                }, 45 * 1000)
            },
            // 监听对方挂断来电
            callRejectedHandler: function (_data) {
                console.log("===== 收到 callRejected 事件: ", _data)
                this.hangupHandler()
                this.callingText = '对方已拒绝'
                Toast(this.callingText);
                //   this.$refs.audioCallingDesc.style.color = 'red'
                //     this.$refs.videoCallingDesc.style.color = 'red'
                if (this.currentPage === 'calling') {
                    this.cleanCallTimer()
                    //const self = this
                    setTimeout(() => {
                        //回到呼叫页面
                        this.currentPage = 'call'
                        this.enterPreviousPage()
                    }, 2 * 1000)
                }
            },

            callAcceptedHandler: function (_data) {
                console.log("===== 收到 callAccepted 事件: ", _data)
                this.cleanCallTimer()
                this.beginMeidaCall()
            },
            // 挂断来电
            ignore: function () {
                this.incomingCallPage = false
                if (this.incomingCallHintTimer) return
                this.$store.commit('videoImHidden', {hidden: false})
                this.cleanIncommingCallTimer()
                console.log("【拒绝】来电")
                this.netcall.control({
                    channelId: this.incomingCallInfo.channelId,
                    command: Netcall.NETCALL_CONTROL_COMMAND_BUSY
                })
                this.netcall.response({
                    accepted: false,
                    beCalledInfo: this.incomingCallInfo
                })
                // 回到之前的界面
                //   this.enterPreviousPage()
            },
            // 接听来电
            answer: function () {
                if (this.incomingCallHintTimer) return
                this.incomingCallPage = false
                this.callingPage = true
                console.log("【接听】来电")
                this.cleanIncommingCallTimer()
                if (this.currentPage === 'called') {
                    //先挂断当前通话
                    this.netcall.hangup()
                    setTimeout(() => {
                        //接听最近的来电，不考虑连续来电的场景
                        this.netcall.response({
                            accepted: true,
                            beCalledInfo: this.incomingCallInfo,
                            sessionConfig: {
                                videoQuality: 0,
                                videoFrameRate: 0,
                                recordAudio: false,
                                recordVideo: false,
                                isHostSpeaker: false,
                                recordType: 0
                            }
                        }).then(data => {
                            console.log("接听成功, data=%o", data)
                            //this.beginMeidaCall()
                        })
                            .catch(error => {
                                console.log("接听失败, error=%o", error)
                                alert(error && error.event && error.event.message || '接听失败')
                                self.cleanCallTimer()
                                self.currentPage = 'call'
                                self.enterPreviousPage()
                            })
                    }, 1 * 1000)
                    return
                }

                //接听最近的来电，不考虑连续来电的场景
                this.netcall.response({
                    accepted: true,
                    beCalledInfo: this.incomingCallInfo,
                    sessionConfig: {
                        videoQuality: 0,
                        videoFrameRate: 0,
                        recordAudio: false,
                        recordVideo: false,
                        isHostSpeaker: false,
                        recordType: 0
                    }
                }).then(data => {
                    console.log("接听成功, data=%o", data)
                    //this.beginMeidaCall()
                })
                    .catch(error => {
                        console.log("接听失败, error=%o", error)
                        alert(error && error.event && error.event.message || '接听失败')
                        self.cleanCallTimer()
                        self.currentPage = 'call'
                        self.enterPreviousPage()
                    })
            },
            // 自己挂断通话
            hangup: function () {
                console.log('自己挂断通话')
                clearInterval(this.callDurationTimer)
                this.netcall.hangup()
                this.slider = false
                this.$store.commit('videoImHidden', this.slider)
                if (this.currentPage === 'called') {
                    this.durationItem = false
                    this.networkItem = false
                    this.callDurationDesc = '通话时长: ' + secondToDate(Date.now() - this.startTime)
                    this.startTime = null
                    this.callDurationItem = true
                    //const self = this
                    this.toastTimer = setTimeout(() => {
                        self.currentPage = 'call'
                        //   self.enterPreviousPage()
                        this.toastTimer = null
                    }, 2 * 1000)
                }
            },
            // 对方挂断通话
            hangupHandler: function () {
                console.log('对方挂断通话')
                clearInterval(this.callDurationTimer)
                this.netcall.hangup()
                this.slider = false
                this.$store.commit('videoImHidden', this.slider)
                if (this.currentPage === 'called') {
                    this.networkItem = false
                    this.callDurationDesc = '通话时长: ' + secondToDate(Date.now() - this.startTime)
                    this.startTime = null
                    this.callDurationItem = true
                    //const self = this
                    this.toastTimer = setTimeout(() => {
                        self.currentPage = 'call'
                        //   self.enterPreviousPage()
                        this.toastTimer = null
                    }, 2 * 1000)
                }
            },
            // 拨打预览画面
            previewLocalCamera: function () {
                console.log('预览本地视频画面')

                function videoPreview(device) {
                    console.log('进入本地视频获取函数');

                    let constraint = {
                        type: Netcall.DEVICE_TYPE_VIDEO
                    }
                    console.log('进入本地视频获取函数1');
                    if (device) {
                        constraint.device = device
                    }
                    console.log('进入本地视频获取函数2');
                    return new Promise((resolve, reject) => {
                        this.netcall.startVideoPreview(constraint).then(data => {
                            console.log('进入本地视频获取函数3');
                            console.warn('获取到视频流: ', data)
                            let videoDom = this.$refs.preview.firstElementChild
                            //自己进行播放，不借助sdk的接口
                            // object-fit: fill; 该css属性 用于控制全屏，关于object-fit请参考https://developer.mozilla.org/zh-CN/docs/Web/CSS/object-fit
                            videoDom.srcObject = data.stream
                            videoDom.setAttribute('x-webkit-airplay', 'x-webkit-airplay')
                            videoDom.setAttribute('playsinline', 'playsinline')
                            videoDom.setAttribute('webkit-playsinline', 'webkit-playsinline')
                            videoDom.preload = 'auto'
                            videoDom.autoplay = 'autoplay'
                            videoDom.muted = true

                            videoDom.play().then((res) => {
                                console.warn('播放执行: ', res)
                            }).catch(error => {
                                console.error('播放器执行失败: ', error)
                            })
                            return resolve()
                            //sdk的播放接口
                            /*
                            self.netcall.setLocalVideoRenderer({
                              view: this.$refs.preview
                            })
                            self.netcall.setLocalRenderMode({
                              width: document.body.clientWidth || document.documentElement.clientWidth,
                              height: document.body.clientHeight || document.documentElement.clientHeight,
                              cut: true
                            })*/
                        }).catch(error => {
                            console.log("获取视频流出错: ", error)
                            reject(error)
                        })
                    })
                }

                if (this.devices.list.length) {
                    console.log("获取摄像头 %s 的画面", this.devices.list[this.devices.index])
                    videoPreview(this.devices.list[this.devices.index])
                    return
                } else if (_isSafari()) {
                    //Safari浏览器比较特殊，需要请求过一次设备之后，才能获取到完整的设备列表
                    videoPreview().then(() => {
                        this.netcall.getDevicesOfType(Netcall.DEVICE_TYPE_VIDEO).then(data => {
                            if (!data || data.length <= 0) {
                                console.log("没有获取到摄像头列表: ", data)
                                return
                            }
                            console.warn("摄像头列表: ", data)
                            this.devices.list = data
                            this.devices.index = 0
                        }).catch(error => {
                            console.log("获取摄像头列表出错: ", error)
                        })
                    }).catch(() => {

                    })
                } else {
                    this.netcall.getDevicesOfType(Netcall.DEVICE_TYPE_VIDEO).then(data => {
                        if (!data || data.length <= 0) {
                            console.log("没有获取到摄像头列表: ", data)
                            return
                        }
                        console.warn("摄像头列表: ", data)
                        this.devices.list = data
                        this.devices.index = 0
                        console.log("获取摄像头 %s 的画面", this.devices.list[this.devices.index])
                        videoPreview(this.devices.list[this.devices.index])
                    }).catch(error => {
                        console.log("获取摄像头列表出错: ", error)
                    })
                }
            },

            openTheMic: function () {
                if (this.toastTimer) return

                console.log('开启mic')
                return new Promise((resolve, reject) => {
                    this.netcall.startDevice({
                        type: WebRTC.DEVICE_TYPE_AUDIO_IN
                    })
                        .then(res => {
                            console.log('开启 mic 成功')
                            this.micOpen = false
                            if (this.callType === 'audio') {
                                // document.getElementById('mic').style.backgroundColor = 'rgba(0,166,0,1)'
                            } else {
                                // document.getElementById('mic').style.backgroundColor = 'rgba(0,166,0,0.55)'
                            }
                            return resolve()
                        })
                        .catch(function (error) {
                            console.log('开启mic失败: ', error);
                            reject(error)
                        })
                })
            },

            closeTheMic: function () {
                if (this.toastTimer) return
                console.log('关闭mic')
                this.netcall.stopDevice(Netcall.DEVICE_TYPE_AUDIO_IN)
                    .then(data => {
                        console.log('关闭 mic 成功')
                        //   document.getElementById('mic').style.backgroundColor = 'rgba(0,0,0,0.55)'
                        this.micOpen = true
                    })
                    .catch(function (error) {
                        console.log('关闭 mic 出错: ', error)
                    })
            },
            // 接通后播放自己的视频
            openTheCamera: function () {
                if (this.toastTimer || this.callType === 'audio') return

                console.warn('开启摄像头')
                console.warn('devices.list: ', this.devices.list)
                console.warn('devices.index: ', this.devices.index)
                this.preview = false
                return new Promise((resolve, reject) => {
                    this.netcall.startDevice({
                        type: WebRTC.DEVICE_TYPE_VIDEO,
                        device: this.devices.list[this.devices.index]
                        /*
                        {
                          deviceId: this.devices.list[this.devices.index]
                        }*/
                    })
                        .then(_data => {
                            console.warn('开启 camera 成功: ', _data)
                            // 自己进行播放，不借助sdk的接口
                            // object-fit: fill; 该css属性 用于控制全屏，关于object-fit请参考https://developer.mozilla.org/zh-CN/docs/Web/CSS/object-fit
                            let videoDom = this.$refs.small.firstElementChild
                            videoDom.srcObject = this.netcall.adapterRef.videoHelperLocal.localCameraStream

                            videoDom.setAttribute('x-webkit-airplay', 'x-webkit-airplay')
                            videoDom.setAttribute('playsinline', 'playsinline')
                            videoDom.setAttribute('webkit-playsinline', 'webkit-playsinline')
                            videoDom.preload = 'auto'
                            videoDom.autoplay = 'autoplay'
                            videoDom.muted = true

                            videoDom.play().then(() => {
                                console.warn('播放执行')
                            }).catch(error => {
                                console.error('播放器执行失败: ', error)
                            })
                            self.cameraOpen = false
                            //   document.getElementById('camera').style.backgroundColor = 'rgba(0,166,0,0.55)'

                            if (_isSafari() && self.devices.list.length && !self.devices.list[0].deviceId) {
                                //Safari浏览器比较特殊，需要请求过一次设备之后，才能获取到完整的设备列表
                                self.netcall.getDevicesOfType(Netcall.DEVICE_TYPE_VIDEO).then(data => {
                                    if (!data || data.length <= 0) {
                                        console.log("没有获取到摄像头列表: ", data)
                                        return
                                    }
                                    console.warn("摄像头列表: ", data)
                                    self.devices.list = data
                                    self.devices.index = 0
                                }).catch(error => {
                                    console.log("获取摄像头列表出错: ", error)
                                })
                            }
                            resolve()

                            //sdk的内部播放接口
                            /*
                            this.netcall.setLocalVideoRenderer({
                              view: this.$refs.small
                            })
                            this.netcall.setLocalRenderMode({
                              width: document.getElementById('small').clientWidth,
                              height: document.getElementById('small').clientHeight,
                              cut: true
                            })
                            */
                        })
                        .catch(function (error) {
                            console.error('开启 camera 出错: ', error)
                        })
                })
            },

            closeTheCamera: function () {
                if (this.toastTimer || this.callType === 'audio') return

                console.log('关闭摄像头')
                this.netcall.stopDevice(Netcall.DEVICE_TYPE_VIDEO)
                    .then(() => {
                        console.log('关闭 camera 成功')
                        //   document.getElementById('camera').style.backgroundColor = 'rgba(0,0,0,0.55)'
                        this.cameraOpen = true
                    })
                    .catch(function (error) {
                        console.log('关闭 camera 出错: ', error)
                    })
            },
            // 切换摄像头
            switchTheCamera: function () {
                console.log('切换摄像头1')
                if (this.toastTimer || this.callType === 'audio') return
                console.log('切换摄像头')
                this.netcall.stopDevice(WebRTC.DEVICE_TYPE_VIDEO).then(() => {
                    console.log('切换摄像头2')
                    console.log('先关闭 camera 成功')
                    console.log('list: ', this.devices.list)
                    console.log('index: ', this.devices.index)
                    if (++this.devices.index >= this.devices.list.length) {
                        this.devices.index = 0
                    }
                    this.netcall.startDevice({
                        type: WebRTC.DEVICE_TYPE_VIDEO,
                        device: this.devices.list[this.devices.index]
                    })
                        .then(_data => {
                            console.log('切换摄像头3')
                            console.log('开启 camera 成功: ', _data)
                            this.$refs.small.firstElementChild.srcObject = this.netcall.adapterRef.videoHelperLocal.localCameraStream
                        })
                        .catch(function (error) {
                            console.error('开启 camera 出错: ', error)
                            this.switchTheCamera()
                        })
                })
                    .catch(function (error) {
                        console.log('关闭 camera 出错: ', error)
                    })
            },
            loudspeaker: function () {
                if (this.toastTimer) return
                if (this.slider) {
                    this.slider = false
                    return
                }
                console.log('设置对端音量')
                this.slider = true

                var box = document.getElementById("rangeslider__handle")
                var x, y;
                var isDrop = false;


                box.ontouchstart = box.onmousedown = function (e) {
                    var e = e || window.event;
                    console.warn('e: ', e)
                    console.warn('box: ', box)
                    if (_isIOS()) {
                        console.warn('ios平台, y: ', e.layerY)
                        console.warn('bak: ', e.pageY)
                        y = e.layerY
                    } else if (_isAndroid()) {
                        console.warn('安卓平台')
                        y = e.touches && e.touches.length && e.touches[0].pageY
                    } else {
                        console.warn('pc平台')
                        y = e.clientY - box.offsetTop;
                    }
                    console.log('上下移动了: ', y)
                    isDrop = true;
                }

                box.ontouchmove = box.onmousemove = function (e) {
                    if (isDrop) {
                        console.warn('ontouchmove e: ', e)
                        var e = e || window.event;
                        var clientY;

                        if (_isIOS()) {
                            console.warn('ios平台')
                            clientY = e.layerY
                        } else if (_isAndroid()) {
                            console.warn('安卓平台')
                            clientY = e.touches && e.touches.length && e.touches[0].pageY
                        } else {
                            console.warn('pc平台')
                            clientY = e.clientY
                        }

                        var moveY = clientY - y;
                        var maxY = 70 || document.documentElement.clientHeight - box.offsetHeight;
                        moveY = Math.min(maxY, Math.max(0, moveY));
                        console.warn('y轴 取值:', moveY)
                        box.style.top = moveY + "px";
                        self.sliderNum = Math.round((70 - moveY) / 7)
                    } else {
                        return;
                    }
                }

                box.ontouchend = box.onmouseup = function () {
                    console.warn('鼠标松开了,设置的音量是: ', self.sliderNum)
                    self.netcall.setPlayVolume(Math.round(self.sliderNum * 255 / 10), self.calleeAccount)
                    isDrop = false;
                }
            },

            swapPlaces: function () {
                console.warn('交换视频窗口')
                this.$refs.small.firstElementChild.srcObject = [this.$refs.large.firstElementChild.srcObject, this.$refs.large.firstElementChild.srcObject = this.$refs.small.firstElementChild.srcObject][0]
            },
            // 播放对方的视频
            remoteTrackHandler: function (_data) {
                console.log('===== 收到remoteTrack事件: ', _data);
                if (_data && _data.track && _data.track.kind == 'audio') {
                    console.log('开始播放 %s 声音', _data.account)
                    this.netcall.startDevice({
                        type: Netcall.DEVICE_TYPE_AUDIO_OUT_CHAT
                    }).then(obj => {
                        console.log('成功播放 %s 声音', _data.account)
                    }).catch(err => {
                        console.log('成功播放 %s 声音 %o', _data.account, err)
                    })
                } else if (_data && _data.track && _data.track.kind == 'video') {
                    console.warn('开始播放 %s 画面', _data.account)
                    //应用层自己播放视频
                    let videoStream = new MediaStream()
                    videoStream.addTrack(_data.track)
                    let videoDom = this.$refs.large.firstElementChild
                    // let videoDom = this.$refs.small.firstElementChild
                    videoDom.setAttribute('x-webkit-airplay', 'x-webkit-airplay')
                    videoDom.setAttribute('playsinline', 'playsinline')
                    videoDom.setAttribute('webkit-playsinline', 'webkit-playsinline')
                    videoDom.preload = 'auto'
                    videoDom.autoplay = 'autoplay'
                    videoDom.muted = true
                    videoDom.srcObject = videoStream

                    videoDom.play().then(() => {
                        console.warn('播放执行')
                    }).catch(error => {
                        console.error('播放器执行失败: ', error)
                    })

                    //sdk的内部播放接口
                    /*
                    this.netcall.startRemoteStream({
                      account: _data.account,
                      node: this.$refs.large
                    })
                    this.netcall.setVideoViewRemoteSize({
                      width: document.getElementById('large').clientWidth,
                      height: document.getElementById('large').clientHeight,
                      cut: true
                    })
                    */
                }
            },

            enterPreviousPage: function () {
                this.hangup()
                // this.$store.commit('videoImHidden',{hidden:false})
                //   console.log('之前的页面: ', this.currentPage)
                //   if (this.currentPage == 'call') {
                //     //进入呼叫页面
                //     this.callPage = true
                //     this.callingPage = false
                //     this.calledPage = false
                //     this.incomingCallPage = false
                //   } else if (this.currentPage === 'calling'){
                //     //进入呼叫中页面
                //     this.callPage = false
                //     this.callingPage = true
                //     this.calledPage = false
                //     this.incomingCallPage = false
                //   } else if (this.currentPage === 'called') {
                //     //进入通话页面
                //     this.callPage = false
                //     this.callingPage = false
                //     this.calledPage = true
                //     this.incomingCallPage = false
                //   }  else if (this.currentPage === 'login') {
                //     //进入登录页面
                //     this.logoIcon = true
                //     this.loginPage = true
                //     this.callPage = false
                //     this.callingPage = false
                //     this.calledPage = false
                //     this.incomingCallPage = false
                //   }
            },


            cleanCallTimer() {
                if (this.callTimeoutTimer) {
                    clearTimeout(this.callTimeoutTimer)
                    this.callTimeoutTimer = null
                }
                if (this.callHintTimer) {
                    clearTimeout(this.callHintTimer)
                    this.callHintTimer = null
                }
            },

            cleanIncommingCallTimer() {
                if (this.incomingCallTimeoutTimer) {
                    clearTimeout(this.incomingCallTimeoutTimer)
                    this.incomingCallTimeoutTimer = null
                }
                if (this.incomingCallHintTimer) {
                    clearTimeout(this.incomingCallHintTimer)
                    this.incomingCallHintTimer = null
                }
            }
        }

    }

    function secondToDate(result) {
        if (result <= 0) {
            return "00:00:00"
        }
        result = result / 1000
        let h = Math.floor(result / 3600) < 10 ? '0' + Math.floor(result / 3600) : Math.floor(result / 3600);
        let m = Math.floor((result / 60 % 60)) < 10 ? '0' + Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
        let s = Math.floor((result % 60)) < 10 ? '0' + Math.floor((result % 60)) : Math.floor((result % 60));
        if (h > 0) {
            return result = h + ":" + m + ":" + s;
        } else {
            return result = m + ":" + s;
        }
    }

    function _isSafari() {
        return /^((?!chrome).)*safari((?!chrome).)*$/gi.test(navigator.userAgent)
    }

    function _isAndroid() {
        return /Android/i.test(navigator.userAgent)
    }

    function _isIOS() {
        console.warn('userAgent: ', navigator.userAgent)
        return /webOS|iPhone|iPod|iOS/i.test(navigator.userAgent)
    }

</script>

<style scoped lang="scss">
    .imVideo {
        position: fixed;
        z-index: 200;
        width: 100%;
        height: 100%;
        top: 50%;
        left: 50%;
        -ms-transform: translateX(-50%) translateY(-50%);
        -webkit-transform: translateX(-50%) translateY(-50%);
        transform: translateX(-50%) translateY(-50%);
        // background: url(../video/cover.jpg) no-repeat;
        background-size: cover;
        background: #000;
    }

    // 播放对方的画面
    .video-called-large-preview-item {
        position: fixed;
        top: 50%;
        left: 50%;
        width: 100vw;
        height: 100vh;

        // width: auto;
        // height: auto;
        -ms-transform: translateX(-50%) translateY(-50%);
        -webkit-transform: translateX(-50%) translateY(-50%);
        transform: translateX(-50%) translateY(-50%);
        // background: url(../video/cover.jpg) no-repeat;
        background-size: cover;

        .large-video {
            width: 100vw;
            height: 100vh;
            object-fit: fill; /*这里是关键*/
        }
    }

    // 接通中播放自己的画面
    .video-called-small-preview-item {
        z-index: 201;
        position: fixed;
        top: 5%;
        right: 10%;
        width: 25%;
        height: 20%;

        .small-video {
            width: 100%;
            height: 100%;
            object-fit: fill; /*这里是关键*/
        }
    }

    // 拨打中预览本地画面
    .video-calling-preview-item {
        z-index: 200;
        position: fixed;
        top: 50%;
        left: 50%;
        width: 100vw;
        height: 100vh;

        // width: auto;
        // height: auto;
        -ms-transform: translateX(-50%) translateY(-50%);
        -webkit-transform: translateX(-50%) translateY(-50%);
        transform: translateX(-50%) translateY(-50%);
        // background: url(../video/cover.jpg) no-repeat;
        background-size: cover;

        .preview {
            width: 100vw;
            height: 100vh;
            object-fit: fill; /*这里是关键*/
        }
    }

    // 挂断
    .hangup-title {
        position: fixed;
        bottom: 10%;
        left: 50%;
        width: 0.6rem;
        height: 0.6rem;
        -ms-transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
        z-index: 201;

        img {
            width: 100%;
            height: 100%;
        }
    }

    // 切换相机
    .switch-camera-title {
        z-index: 201;
        position: absolute;
        top: 3%;
        left: 8%;
        width: 0.28rem;
        height: 0.28rem;

        img {
            width: 100%;
            height: 100%;
        }
    }

    // 来电页面
    .incoming-call-page {
        position: absolute;
        bottom: 10%;
        left: 50%;
        -ms-transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
        display: flex;

        .incoming-ignore-btn {
            margin: 0 0.4rem;
            width: 0.6rem;
            height: 0.6rem;

            img {
                width: 100%;
            }
        }

        .incoming-answer-btn {
            margin: 0 0.4rem;

            width: 0.6rem;
            height: 0.6rem;

            img {
                width: 100%;
            }
        }
    }

    // 拨打对象的头像
    .userInfo {
        position: fixed;
        top: 10%;
        left: 50%;
        -ms-transform: translateX(-50%);
        -webkit-transform: translateX(-50%);
        transform: translateX(-50%);
        text-align: center;

        img {
            width: 0.8rem;
            height: 0.8rem;
            border-radius: 50%;
        }

        div {
            color: #fff;
            font-size: 0.18rem;
        }
    }

    .durationText {
        position: absolute;
        z-index: 202;
        color: #fff;
        font-size: 0.2rem;
    }
</style>
